/*Hm9gUKDDwtNjV7Mk8onAzuEHPbfUwAnfWyNcAQ3p3qQVroIHGgbouA/v3HeA4/n7*/
import { ajax, toast, cacheTools, print, output } from 'nc-lightapp-front';
import constants from '../../constants';

import ampub from 'ampub';
import fa from 'fa';

import CreateNCUploade from 'uap/common/components/CreateNCUploade';
const { createNCUploader, show: ncUploaderShow, close: ncUploaderClose } = CreateNCUploade;

import rowSelected from './rowSelected';
import searchBtnClick from './searchBtnClick';
import { doDeleteBeforeCheck } from '../../validator';

const {
	components: {
		queryAboutUtils: { openEquipCardByPk, openEquipCardByFaCardPk },
		queryVocherUtils: { queryAboutVoucher }
	},
	utils: {
		msgUtils: { showConfirm, MsgConst, showMessage, showErrorMessageByRes },
		listUtils: { batchRefresh },
		multiLangUtils: { getMultiLangByID }
	}
} = ampub;
const { fa_components: { CardLinkToBillUtil: { CardLinkToBill } } } = fa;

const {
	BILL_SOURCE_TYPES,
	AREA: { LIST: { GRID_AREA: tableId } },
	LIST_BTNS: {
		HEAD: {
			REFRESH,
			DELETE,
			COPY,
			Attachment,
			QueryAboutCard,
			QueryAboutVoucher,
			QueryAboutBusiness,
			PRINT_CHILD,
			PRINT_NOCHILD,
			PRINT_LIST,
			Output
		}
	}
} = constants;

export default function buttonClick(props, id) {
	const that = this;
	switch (id) {
		//表头刷新
		case REFRESH:
			doRefresh(that);
			break;

		//表头复制
		case COPY:
			doCopy(that);
			break;

		//打印-带副卡
		case PRINT_CHILD:
			doPrintChild(that);
			break;

		//打印-不带副卡
		case PRINT_NOCHILD:
			doPrintNoChild(that);
			break;

		//打印-清单
		case PRINT_LIST:
			doPrintList(that);
			break;

		//输出
		case Output:
			doOutput(that);
			break;

		//表头删除
		case DELETE:
			showConfirm.call(this, props, {
				type: MsgConst.Type.DelSelect,
				beSureBtnClick: () => {
					batchDelete(props);
				}
			});

			break;

		//联查设备卡片
		case QueryAboutCard:
			queryAboutCard(props);
			break;

		//附件
		case Attachment:
			attachment.call(this, props);
			break;

		//联查凭证
		case QueryAboutVoucher:
			let { props: { pageConfig: { appid: appcode } } } = this;
			queryAboutVoucher(props, tableId, 'pk_card', appcode, true);
			break;

		//联查来源单据
		case QueryAboutBusiness:
			billreview.call(that);
			break;

		//卡片交易类型按钮点击, pagecode就是交易类型
		default:
			openCard(that, id);
			break;
	}
}

//根据选择的交易类型打开卡片
function openCard(that, id) {
	linkToCard(that.props, {
		status: constants.UISTATE.ADD,
		transiType: id,
		pagecode: id
	});
}

//行删除
function deleteLine(props, row) {
	let checkRet = doDeleteBeforeCheck(row.values);
	if (checkRet) {
		showMessage(props, { content: checkRet, color: 'danger' });
	} else {
		doDelete(props, [ row ]);
	}
}

//批量删除
function batchDelete(props) {
	let rowsWillDel = props.table.getCheckedRows(tableId);
	if (rowsWillDel && rowsWillDel.length) {
		rowsWillDel = rowsWillDel.map((row) => row.data);
		let checkErrs = [];
		rowsWillDel.forEach((row) => {
			let err = doDeleteBeforeCheck(row.values);
			if (err) {
				checkErrs.push(err);
			}
		});

		if (checkErrs.length) {
			if (checkErrs.length === 1) {
				toast({ content: checkErrs[0], color: 'danger' });
			} else {
				toast({
					color: 'danger',
					groupOperation: true,
					groupOperationMsg: checkErrs,
					TextArr: [
						getMultiLangByID('amcommon-000005'),
						getMultiLangByID('amcommon-000006'),
						getMultiLangByID('amcommon-000007')
					] /* 国际化处理： ['展开', '收起', '关闭'] */
				});
			}
		} else {
			doDelete(props, rowsWillDel);
		}
	} else {
		/*国际化处理：请选择需要删除的单据*/
		showMessage(props, { type: MsgConst.Type.ChooseDelete });
	}
}

function doCopy(that) {
	let rows = that.props.table.getCheckedRows(tableId);
	if (rows && rows.length) {
		const pk_card = rows[0].data.values.pk_card.value;
		that.facardCopy.showCopyCardDialog(that, pk_card, rows[0].data.values);
	} else {
		/*国际化处理：请选择需要复制的单据*/
		showMessage(that.props, { type: MsgConst.Type.ChooseCopy });
	}
}

/**
 * 执行删除
 *
 * @props props
 * @param rows 需要删除的行数组
 */
function doDelete(props, rows) {
	if (rows) {
		//获取pk、ts
		let pks = [];
		let tss = [];
		rows.forEach((row) => {
			pks.push(row.values.pk_card.value);
			tss.push(row.values.ts.value);
		});

		const data = {
			pks: pks.join(','),
			tss: tss.join(',')
		};
		ajax({
			url: constants.URL.DELETE,
			data,
			success: (res) => {
				let { success, data } = res;
				if (success) {
					let { allSuccess, message, suceessArr, failure } = data;
					if (failure) {
						showMessage(props, { content: failure, color: 'danger' });
					} else {
						if (message && message.length === 1) {
							toast({
								color: 'success',
								title: message[0]
							});
						} else {
							toast({
								color: 'danger',
								content: message.shift(),
								groupOperation: true,
								groupOperationMsg: message,
								TextArr: [
									getMultiLangByID('amcommon-000005'),
									getMultiLangByID('amcommon-000006'),
									getMultiLangByID('amcommon-000007')
								] /* 国际化处理： ['展开', '收起', '关闭'] */
							});
						}

						//删除成功后, 同步缓存和表格数据
						let { deleteCacheId } = props.table;
						if (suceessArr && suceessArr.length) {
							let pkcardsToDel = [];
							suceessArr.map((pk_cardAndpk_accbook) => {
								//删除缓存
								deleteCacheId(tableId, pk_cardAndpk_accbook);
								//删除表格中的数据
								let pk_card = pk_cardAndpk_accbook.split('_')[0];
								pkcardsToDel.push(pk_card);
							});

							let indexsToDel = [];
							let allData = props.table.getAllTableData(tableId);
							allData.rows.map((row, index) => {
								const pk_card = row.values.pk_card.value;
								if (pkcardsToDel.includes(pk_card)) {
									indexsToDel.push(index);
								}
							});
							props.table.deleteTableRowsByIndex(tableId, indexsToDel);
						}
						//更新按钮状态
						rowSelected(props, tableId);
					}
				}
			},
			error: (err) => {
				showErrorMessageByRes(props, res);
			}
		});
	}
}

//跳转到卡片态
function linkToCard(props, param = {}) {
	let defaultParam = {
		status: constants.UISTATE.BROWSE
	};
	let am_source = props.getUrlParam('am_source');
	let menu_name = props.getUrlParam('nccloud_menu_name_self');

	param = Object.assign(defaultParam, param);
	if (am_source) {
		param.am_source = am_source;
	}
	if (menu_name) {
		param.nccloud_menu_name_self = menu_name;
	}
	props.pushTo('/card', param);
}

//刷新
function doRefresh(that) {
	batchRefresh.call(that, that.props, searchBtnClick);
}

function doPrintChild(that) {
	let nodekey = '201201504A_child';
	let url = constants.URL.PRINT_CARD;
	doPrint(that, nodekey, url);
}

function doPrintNoChild(that) {
	let nodekey = '201201504A_nochild';
	let url = constants.URL.PRINT_CARD;
	doPrint(that, nodekey, url);
}

function doPrintList(that) {
	let nodekey = '201201504A_list';
	let url = constants.URL.PRINT_LIST;
	doPrint(that, nodekey, url);
}

//打印
function doPrint(that, nodekey, printUrl) {
	let printData = getPrintData.call(that, that.props, 'print');
	printData.nodekey = nodekey || printData.nodekey;
	let url = printUrl || constants.URL.PRINT_CARD;
	if (!printData) {
		/*国际化处理：请选择需要打印的数据*/
		showMessage(that.props, { type: MsgConst.Type.ChoosePrint });
		return;
	}
	print(
		'pdf', // 支持两类：'html'为模板打印，'pdf'为pdf打印
		url, // 后台打印服务url
		printData
	);
}

//输出
function doOutput(that) {
	let printData = getPrintData.call(that, that.props, 'output');
	//输出默认为不带副卡的模板
	printData.nodekey = '201201504A_nochild';
	if (!printData) {
		/*国际化处理：请选择需要输出的数据*/
		showMessage(that.props, { type: MsgConst.Type.ChooseOutput });
		return;
	}
	output({
		url: constants.URL.PRINT_CARD,
		data: printData
	});
}

/*
 * 获取打印数据
 */
function getPrintData(props, outputType = 'print') {
	const { pageConfig } = this.props;
	let printNodekey = null;

	let checkedRows = props.table.getCheckedRows(tableId);
	if (!checkedRows || checkedRows.length == 0) {
		return false;
	}
	let pks = [];
	checkedRows.map((item) => {
		let pk_card = item.data.values['pk_card'].value;
		let pk_accbook = item.data.values['pk_accbook'].value;
		pks.push(pk_card + '_' + pk_accbook);
	});
	let printData = {
		filename: pageConfig.title, // 文件名称
		appcode: '201201504A',
		nodekey: printNodekey, // 模板节点标识
		oids: pks, // 需要打印数据主键
		outputType // 输出类型
	};
	return printData;
}

//联查设备卡片
function queryAboutCard(props) {
	let checkedRows = props.table.getCheckedRows(tableId);
	if (!checkedRows || !checkedRows.length) {
		/*国际化处理：请选择需要联查的卡片*/
		showMessage(props, { content: getMultiLangByID('201201504A-000030'), color: 'warning' });
		return;
	}
	//默认选择第一条进行联查
	let row = checkedRows[0];
	let pk_equip = row.data.values.pk_equip && row.data.values.pk_equip.value;
	if (pk_equip) {
		let pk_card = row.data.values.pk_card && row.data.values.pk_card.value;
		openEquipCardByFaCardPk(props, pk_card);
	} else {
		/*国际化处理：选中的数据中第一条没有关联设备卡片*/
		showMessage(props, { content: getMultiLangByID('201201504A-000031'), color: 'warning' });
	}
}

/**
 * 附件上传
 * @param  props
 */
function attachment(props) {
	let checkedrows = props.table.getCheckedRows(tableId);
	if (!checkedrows || !checkedrows.length) {
		/*国际化处理：请选择一行数据*/
		showMessage(props, { type: MsgConst.Type.ChooseOne });
		return;
	}
	// billNo 是资产编码
	let billNo = checkedrows[0].data.values['asset_code'].value;
	// billNo 是卡片主键
	let billId = checkedrows[0].data.values['pk_card'].value;
	ncUploaderShow.call(this, 'uploader', {
		billId: 'fa/card/' + billId,
		billNo
	});
}

//单据追溯
function billreview() {
	const { props, props: { table } } = this;
	let checkedrows = table.getCheckedRows(tableId);
	if (!checkedrows || !checkedrows.length) {
		/*国际化处理：请选择一行数据*/
		showMessage(null, { type: MsgConst.Type.ChooseOne });
		return;
	}

	//默认选择第一条进行联查
	let [
		{
			data: {
				values: {
					//获取卡片来源
					bill_source: { value: bill_source },
					//获取来源主键
					pk_bill_src: { value: pk_src },
					bill_code_src: { value: bill_code_src },
					// 来源单据交易类型
					transi_type_source: { value: transi_type_source }
				}
			}
		}
	] = checkedrows;

	//卡片来源交易类型 有默认值handin
	if (transi_type_source === BILL_SOURCE_TYPES.handin_src) {
		transi_type_source = null;
	}

	if (bill_source === BILL_SOURCE_TYPES.inventory_src) {
		pk_src += '<:>' + bill_code_src;
	}

	let type_src = transi_type_source || bill_source;

	if (bill_source !== BILL_SOURCE_TYPES.handin_src) {
		if (pk_src && type_src && !type_src.startsWith(BILL_SOURCE_TYPES.equip_src)) {
			CardLinkToBill.call(this, props, pk_src, type_src);
		} else {
			/*国际化处理：该单据的来源单据号错误*/
			showMessage(props, { content: getMultiLangByID('201201504A-000021'), color: 'warning' });
		}
	} else {
		/*国际化处理：该单据没有来源单据*/
		showMessage(props, { content: getMultiLangByID('201201504A-000022'), color: 'warning' });
	}
}

export { doRefresh, linkToCard, deleteLine };

/*Hm9gUKDDwtNjV7Mk8onAzuEHPbfUwAnfWyNcAQ3p3qQVroIHGgbouA/v3HeA4/n7*/